package com.enterprise.web;

import com.assg2.dao.DaoMovie;
import com.movie.Movie;
import java.util.Date;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Kevin
 */
public class AddMovie extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private static final String TMP_DIR_PATH = "/import/Kamen/1/aenr397/Downloads/temp";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "/images/posters";
    private File destinationDir;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        tmpDir = new File(TMP_DIR_PATH);
        if (!tmpDir.isDirectory()) {
            throw new ServletException(TMP_DIR_PATH + " is not a directory");
        }
        String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        destinationDir = new File(realPath);
        if (!destinationDir.isDirectory()) {
            throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
        }

    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        /*
         *Set the size threshold, above which content will be stored on disk.
         */
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
		/*
         * Set the temporary directory to store the uploaded files of size above threshold.
         */
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);


        try {
            Movie movie = new Movie();

            String title = null;
            String director = null;
            String duration = null;
            String agerating = null;
            String synopsis = null;
            String genre = null;
            String year = null;
            String month = null;
            String day = null;
            String endyear = null;
            String endmonth = null;
            String endday = null;
            String url = null;
            String posterName = null;

            List items = uploadHandler.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                /*
                 * Handle Form Fields.
                 */
                if (item.isFormField()) {
                    if ("title".matches(item.getFieldName())) {
                        title = item.getString();
                    } else if ("director".matches(item.getFieldName())) {
                        director = item.getString();
                    } else if ("duration".matches(item.getFieldName())) {
                        duration = item.getString();
                    } else if ("agerating".matches(item.getFieldName())) {
                        agerating = item.getString();
                    } else if ("synopsis".matches(item.getFieldName())) {
                        synopsis = item.getString();
                    } else if ("genre".matches(item.getFieldName())) {
                        genre = item.getString();
                    } else if ("url".matches(item.getFieldName())) {
                        url = item.getString();
                    }else if ("year".matches(item.getFieldName())) {
                        year = item.getString();
                    } else if ("month".matches(item.getFieldName())) {
                        month = item.getString();
                    } else if ("day".matches(item.getFieldName())) {
                        day = item.getString();
                    } else if ("endyear".matches(item.getFieldName())) {
                        endyear = item.getString();
                    } else if ("endmonth".matches(item.getFieldName())) {
                        endmonth = item.getString();
                    } else if ("endday".matches(item.getFieldName())) {
                        endday = item.getString();
                    }

                } else {
                    //Handle Uploaded files.
                    posterName = item.getName();
//                    out.println("Field Name = " + item.getFieldName()
//                            + ", File Name = " + item.getName()
//                            + ", Content type = " + item.getContentType()
//                            + ", File Size = " + item.getSize());
//                    out.write("<img width='100px' src='images/posters/" + item.getName() + "' />");
                    /*
                     * Write file to the ultimate location.
                     */
                    File file = new File(destinationDir, item.getName());
                    item.write(file);
                }
            }

            Date beginDate = new java.sql.Date(Integer.parseInt(year)- 1900, Integer.parseInt(month) - 1,Integer.parseInt(day));
            Date endDate = new java.sql.Date(Integer.parseInt(endyear) - 1900, Integer.parseInt(endmonth) - 1, Integer.parseInt(endday));
            int genreId = Integer.parseInt(genre);
            movie.setTitle(title);
            movie.setDirector(director);
            movie.setDuration(Integer.parseInt(duration));
            movie.setAgerating(agerating);
            movie.setSynopsis(synopsis);
            movie.setRelaseDate(beginDate);
            movie.setUntil(endDate);
            movie.setGenreIdgenre(genreId);
            movie.setPoster(posterName);
            movie.setVideo(url);
            DaoMovie dm = new DaoMovie();
            dm.save(movie);


//            
            request.getSession().setAttribute("addmovie", movie);

            request.getRequestDispatcher("addActor.jsp").forward(request, response);







        } catch (FileUploadException ex) {
            log("Error encountered while parsing the request", ex);
        } catch (Exception ex) {
            log("Error encountered while uploading file", ex);
        } finally {
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
